package com.seari.gena.ciosClient;

import java.nio.charset.Charset;

import com.seari.bean.BaseClient;
import com.seari.gena.ciosClient.handler.CIOSUpdateClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class CIOSUpdateClient extends BaseClient {
	
	private String sid;
	
	public CIOSUpdateClient() {
		super();
	}

	public CIOSUpdateClient(String host, int port,String sid) {
		this.host = host;
		this.port = port;
		this.sid = sid;
	}

	@Override
	public void setup() throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group) // 注册线程池
					.channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类
					.option(ChannelOption.SO_KEEPALIVE, true)
					.handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							System.out.println("正在连接中...");
							ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
							ch.pipeline().addLast(new CIOSUpdateClientHandler(sid));
							ch.pipeline().addLast(new ByteArrayEncoder());
							ch.pipeline().addLast(new ChunkedWriteHandler());
						}
					});
			ChannelFuture cf = b.connect(host, port).sync(); // 异步连接服务器
			System.out.println("服务端连接成功..."); // 连接完成

			cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
			System.out.println("连接已关闭.."); // 关闭完成

		} finally {
			group.shutdownGracefully().sync(); // 释放线程池资源
		}
	}

	@Override
	public void reset() throws Exception {
		if (null != channel) {
			channel.close();
		}
		setup();
	}
	
	public static void main(String[] args) throws Exception{
		new CIOSUpdateClient("172.26.200.6", 52213,"123456").setup();
	}
	

}